package com.hll.spring_book.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hll.spring_book.annotion.logAnno;
import com.hll.spring_book.pojo.Book;
import com.hll.spring_book.service.book.BookService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Mr.Hu
 * @create: 2021-03-17 22:23
 */
@RequestMapping("/book")
@RestController
public class BookController {
  @Resource private BookService bookService;
  /** */
  @PostMapping("/queryBooksByLimit")
  /*default value，如果方get请求不传参数，就默认(如果不设置，代表必须传参)， value是参数名*/
  public PageInfo<Book> queryBookByLimit(
      @RequestParam(defaultValue = "1", value = "pageNo") Integer pageNo,
      @RequestParam(defaultValue = "5", value = "pageSize") Integer pageSize,
      @RequestParam(value = "name", required = false) String name,
      @RequestParam(value = "category", required = false) Integer category) {
    PageHelper.startPage(pageNo, pageSize); /*分页插件，mapper看起来是查找全部，但被干预了*/
    Book book = new Book();
    book.setName(name);
    book.setCategory(category);
    return new PageInfo<>(bookService.queryAll(book));
  }

  @PostMapping("queryAllBooks")
  public List<Book> queryAllBooks(
      @RequestParam(value = "name", required = false) String name,
      @RequestParam(value = "category", required = false) Integer category) {
    Book book = new Book();
    book.setName(name);
    book.setCategory(category);
    return bookService.queryAll(book);
  }

  /*查看name-author书籍是否存在*/
  @PostMapping("/checkExist")
  public boolean checkBookExist(
      @RequestParam("name") String name, @RequestParam("author") String author) {
    return bookService.isBookExist(name, author);
  }

  @PostMapping("/queryBookById")
  /*requestParam是从请求url中取参数，post不能用*/
  public Book getBookById(@RequestParam("id") Integer id) {
    return bookService.queryById(id);
  }

  /*value写成#obj.attribute形式可以获取参数的属性值，也可单独写成 #param 获取同名参数值*/
  @logAnno(description = "新增书籍", value = "#book.id") /*因为after method后才打印日志，所以此时book.id存在*/
  @PostMapping("/addBook")
  public boolean addBook(@RequestBody Book book) {
    if (!checkBookExist(book.getName(), book.getAuthor())) {
      book = bookService.insert(book);
      return book != null;
    }
    return false;
  }

  @logAnno(value = "#book.id", description = "修改书籍")
  @PostMapping("/updateBook")
  public boolean modifyBook(@RequestBody Book book) {
    return bookService.update(book) != null;
  }

  @logAnno(description = "删除书籍", value = "#id")
  @PostMapping("/deleteBook")
  public boolean deleteBook(@RequestParam(value = "id") Integer id) {
    return bookService.deleteById(id);
  }
}
